/**
 * 
 */
package com.bwda.dsrs.systemservice.eam.controller;

import com.bwda.dsrs.systemservice.eam_client.model.OauthAccessToken;
import com.bwda.dsrs.systemservice.eam_client.model.OauthParams;
import com.bwda.dsrs.systemservice.eam_client.model.OauthRespError;
import com.bwda.dsrs.systemservice.eam_client.util.MatcherUtil;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yahui
 *
 */
public class GetTokenService {
	
	public Map<String, Object> getToken(OauthParams reqParams){
		OauthRespError error = new OauthRespError();
		Map<String, Object> returnMap = new HashMap<String, Object>(16);
		if (reqParams == null || !MatcherUtil.isUrlMatcher(reqParams.getAuthUrl())) {
			
			error.setError("request parameter excption");
			error.setErrorDescription("request parameter excption");
			returnMap.put("statusCode", "201");
			returnMap.put("error", error);
		}
		String json = null;
		HttpResponse httpResp = null;
		
		Map<String, Object> map = new HashMap<String, Object>(16);
		HttpClient client = new DefaultHttpClient();
		client.getParams().setIntParameter("http.socket.timeout",10000);
		HttpPost post = new HttpPost(reqParams.getAuthUrl());
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("client_id", reqParams
				.getClientId()));
		params.add(new BasicNameValuePair("grant_type", reqParams
				.getGrantType()));
		params.add(new BasicNameValuePair("code", reqParams.getCode()));
		params.add(new BasicNameValuePair("redirect_uri",reqParams.getRedirectUri()));
		
		
		
		try {
			post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			httpResp = client.execute(post);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Gson gson = new Gson();
		try {
			System.out.println(httpResp==null);
			if(httpResp !=null){
			json = EntityUtils.toString(httpResp.getEntity());
			}
			System.out.println("token json==="+json);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try{
		if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			if (json != null && !"".equals(json.trim())) {
			Map<String, Object> accessTokenMap = gson.fromJson(json,
					new TypeToken<Map<String, String>>() {
					}.getType());
			if(accessTokenMap != null && !"".equals(accessTokenMap)){

				OauthAccessToken accessToken = new OauthAccessToken();
				accessToken.setAccessToken((String) accessTokenMap
						.get("access_token"));
				accessToken
						.setExpiresIn((String) accessTokenMap.get("expires_in"));
				returnMap.put("accessToken", accessToken);
				returnMap.put("statusCode", "200");
			
			}else{
				error.setError("return is null");
				error.setErrorDescription("return is null");
				returnMap.put("statusCode", "201");
				returnMap.put("error", error);
			}
		}
		}else{

			if (json != null && !"".equals(json.trim())) {
				map = gson.fromJson(json,
						new TypeToken<Map<String, String>>() {
						}.getType());
				if (map != null && !"".equals(map)) {
					OauthRespError oauthError = new OauthRespError();
					oauthError.setError((String) map.get("error"));
					oauthError.setErrorDescription((String) map
							.get("error_description"));
					returnMap.put("error", oauthError);
					returnMap.put("statusCode", "201");
				}else{
					error.setError("return is null");
					error.setErrorDescription("return is null");
					returnMap.put("statusCode", "201");
					returnMap.put("error", error);
				}
			}else{
				error.setError("return is null");
				error.setErrorDescription("return is null");
				returnMap.put("statusCode", "201");
				returnMap.put("error", error);
			}
		
		}
		}catch (JsonParseException e) {
			error.setError("returns the parameter formatting errors ");
			error.setErrorDescription("returns the parameter formatting is not json ");
			returnMap.put("statusCode", "201");
			returnMap.put("error", error);

		}catch(Exception e){
			e.printStackTrace();
		}
		return returnMap;
	}

}
